﻿using System;
using System.Collections.Generic;
using System.Text;
using POI.eTransmittal.Enitity;
using System.Net.Mail;
using DevExpress.Xpo;
using System.Diagnostics;
using System.Net;
using DevExpress.Data.Filtering;
using System.IO;

namespace POI.eTransmittal.BusinessRule
{
    public abstract class EmailEngineBase
    {
        protected string smtp_address;
        protected int smtp_port;
        protected string from_address;

        protected EmailEngineBase(string smtp_address, int smtp_port, string from_address)
        {
            this.smtp_address = smtp_address;
            this.smtp_port = smtp_port;
            this.from_address = from_address;
        }

        public abstract void SendEmail(string send_to, string send_cc, string send_from, string subject, string body);
        public abstract void SendEmail(string send_to, string send_cc, string send_from, string subject, string body,string filePath);
    }

    public class POIEmailSender : EmailEngineBase
    {
        private bool isLocal = false;
        private string user;
        private string pass;
        private bool useSSL;
        MailMessage mail;
        public POIEmailSender()
            : base(string.Empty, 0,"")
        {

            UnitOfWork  uow = new UnitOfWork();
            smtp_port = Convert.ToInt32(CommonBusinessRules.GetGeneralParameterByTitle(GeneralParameter.SMTP_PORT, uow));
            smtp_address = CommonBusinessRules.GetGeneralParameterByTitle(GeneralParameter.SMTP_SERVER, uow);
            isLocal = Convert.ToBoolean(CommonBusinessRules.GetGeneralParameterByTitle(GeneralParameter.SMTP_USE_LOCAL, uow));
            if (isLocal)
            {
                user = CommonBusinessRules.GetGeneralParameterByTitle(GeneralParameter.SMTP_USER_NAME, uow);
                pass = CommonBusinessRules.GetGeneralParameterByTitle(GeneralParameter.SMTP_USER_PASS, uow);
            }
            useSSL = Convert.ToBoolean(CommonBusinessRules.GetGeneralParameterByTitle(GeneralParameter.SMTP_USE_SSL, uow));
        }

        public void PrepareEmail(string send_to, string send_cc, string send_from, string subject, string body)
        {
            mail = new MailMessage();
            if (send_from == "")
                send_from = from_address;
            mail.From = new MailAddress(send_from);
            mail.Subject = subject;
            mail.Body = body;
            mail.IsBodyHtml = true;
            mail.Priority = MailPriority.Normal;
           
            if (!String.IsNullOrEmpty(send_to))
            {
                foreach (string email in send_to.Split(';'))
                {
                    if (email != "")
                        mail.To.Add(email);
                }
            }

            if (!String.IsNullOrEmpty(send_cc))
            {
                foreach (string email in send_cc.Split(';'))
                {
                    if (email != "")
                        mail.CC.Add(email);
                }
            }
            mail.Sender = mail.From;
        }

        public override void SendEmail(string send_to, string send_cc, string send_from, string subject, string body)
        {
            PrepareEmail(send_to, send_cc, send_from, subject, body);
            SendSmtpEmail();
        }
      

        public void SendSmtpEmail()
        {
            SmtpClient client = new SmtpClient();
            client.DeliveryMethod = SmtpDeliveryMethod.Network ;
            client.Port = smtp_port;
            client.Host = smtp_address;
       
            if (client.Port != 25)
                client.EnableSsl = true;
            if (!(String.IsNullOrEmpty(user) || String.IsNullOrEmpty(pass)))
                client.Credentials = new NetworkCredential(user, pass);
#if !DEBUG
            client.Send(mail);
#else
            Debug.Print("From: {0}\r\nTo: {1}\r\nSubject: {2}\r\nBody: \r\n{3}",
                "eTransmittal System", mail.To.ToString(), mail.Subject, mail.Body);
#endif
        }

        public override void SendEmail(string send_to, string send_cc, string send_from, string subject, string body, string filePath)
        {
            throw new NotImplementedException();
        }
    }
    public class IncomingNotificationSender
    {
        EmailEngineBase  engine;
        IncomingTransmittal transmittal;
        string body = "";
        public IncomingNotificationSender(IncomingTransmittal trans,string body)
        {
            transmittal = trans;
            engine = new  EmailGoogleSender(); //new POIEmailSender();

        }
        public IncomingNotificationSender(IncomingTransmittal trns, EmailEngineBase engine)
        {
            transmittal = trns;
            this.engine = engine;
        }
        public IncomingNotificationSender(IncomingTransmittal trn)
        {
            // TODO: Complete member initialization
            transmittal = trn;
            engine = new EmailGoogleSender();//engine = new POIEmailSender();
        }
        public void Send()
        {
            GeneralParameter prm = transmittal.Session.FindObject<GeneralParameter>(CriteriaOperator.Parse("ParamTitle = ?", GeneralParameter.INCOMING_EMAIL_BODY));

            if (prm == null)
            {
                prm = new GeneralParameter(transmittal.Session);
                prm.ParamDataType = typeof(string).Name;
                prm.ParamTitle = GeneralParameter.INCOMING_EMAIL_BODY;
                prm.ParamValue = @"<p>Dear All,</p><p>We have received the incoming transmittal that may related to you.<br /><i>Please click <a href=""{0}"">here</a> to view the details.</i></p>Thank you,<br />IM Data Management";
                prm.Save();
                transmittal.Session.CommitTransaction();

            }
            string unc = transmittal.GetUNC_FileLink();
            string emailBody = string.Format(prm.ParamValue, unc);
            string sendto=transmittal.GetAttnEmailAddress();
            string sendcc=transmittal.GetCcEmailAddress();
            engine.SendEmail(sendto, sendcc, "", transmittal.Subject, emailBody);

        }
        public void testSend()
        {
            GeneralParameter prm = transmittal.Session.FindObject<GeneralParameter>(CriteriaOperator.Parse("ParamTitle = ?", GeneralParameter.INCOMING_EMAIL_BODY));

            if (prm == null)
            {
                prm = new GeneralParameter(transmittal.Session);
                prm.ParamDataType = typeof(string).Name;
                prm.ParamTitle = GeneralParameter.INCOMING_EMAIL_BODY;
                prm.ParamValue = @"<p>Dear All,</p><p>We have received the incoming or outgoing transmittal that may related to you.<br /><i>Please click <a href=""{0}"">here</a> to view the details.</i></p>Thank you,<br />IM Data Management";
                prm.Save();
                transmittal.Session.CommitTransaction();

            }
            string unc = transmittal.GetUNC_FileLink();
            string emailBody = string.Format(prm.ParamValue, unc);
            string sendto = "adam.ramdhani@ptgdi.com";
            //transmittal.GetAttnEmailAddress();
           // string sendcc = transmittal.GetCcEmailAddress();
            engine.SendEmail(sendto, "", "", transmittal.Subject, emailBody);
        }
    }
    public class OutgoingNotificationSender
    {
        OutgoingTransmittal trans;
        EmailEngineBase engine;
        public OutgoingNotificationSender(OutgoingTransmittal trans)
        {
            this.trans = trans;
            engine = new EmailGoogleSender();
        }
        public void SendNotification(string url)
        {
            GeneralParameter prm = trans.Session.FindObject<GeneralParameter>(CriteriaOperator.Parse("ParamTitle = ?", GeneralParameter.OUTGOING_NOTIFICATION));
            if (prm == null)
            {
                prm = new GeneralParameter(trans.Session);
                prm.ParamDataType = typeof(string).Name;
                prm.ParamTitle = GeneralParameter.OUTGOING_NOTIFICATION;
                prm.ParamValue = @"<p>Dear Coordinator,</p><p>There is an outgoing transmittal, that require your attention.<br /><i>Please click <a href=""{0}"">here</a> to view the details.</i></p>Thank you,<br />IM Data Management";
                prm.Save();
                trans.Session.CommitTransaction();
            }
            string emailBody=prm.ParamValue;
            prm = trans.Session.FindObject<GeneralParameter>(CriteriaOperator.Parse("ParamTitle = ?", GeneralParameter.COORDINATOR_EMAIL_ADDRESS));
            if (prm == null)
            {
                prm = new GeneralParameter(trans.Session);
                prm.ParamDataType = typeof(string).Name;
                prm.ParamTitle = GeneralParameter.COORDINATOR_EMAIL_ADDRESS;
                prm.ParamValue = "jamaludin@premier-oil.com";
                prm.Save();
                trans.Session.CommitTransaction();
            }
            string send_to = prm.ParamValue;
            prm = trans.Session.FindObject<GeneralParameter>(CriteriaOperator.Parse("ParamTitle = ?", GeneralParameter.COORDINATOR_EMAIL_ADDRESS));
            engine.SendEmail(send_to,"","ptgdi_dummy@ptgdi.com","Outgoing Fax Waiting",string.Format(emailBody,url));
        }
    }
    public class FaxSender
    {
        OutgoingTransmittal trans;
        EmailEngineBase engine;
        public FaxSender(OutgoingTransmittal trns)
        {
            trans = trns;
            engine = new EmailGoogleSender();
        }
        public void SendToFax()
        {
            string Fax_expression = CommonBusinessRules.GetGeneralParameterByTitle(GeneralParameter.FAX_EXPRESSION, trans.Session);
            string sendto = Fax_expression.Replace("#fax#", trans.FaxNo);



            engine.SendEmail(sendto, "", "", trans.Subject, "", trans.FaxFileLink);
       
            //if (string.Equals(_View.PDFPath, string.Empty))
            //    throw new Exception("PDF file is required");
            //FileInfo fi = new FileInfo(_View.PDFPath);
            //if (fi.Exists)
            //{
            //    Outlook.MailItem mailFax = (Outlook.MailItem)OutApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
            //    string faxPattern = db.GetFaxPattern();
            //    if (isNumber(_View.FaxNo))
            //        mailFax.To = faxPattern.Replace(DataAccess.Database.FAX_TEMPLATE, _View.FaxNo);
            //    else
            //    {
            //        mailFax.Recipients.Add(View.FaxNo);
            //        mailFax.Recipients.ResolveAll();
            //    }
            //    mailFax.Subject = _View.Subject;
            //    mailFax.BodyFormat = Outlook.OlBodyFormat.olFormatHTML;
            //    // mailOnshore.HTMLBody = db.GetBodyAttnEmail(sharedFileName, OriginalFileName);
            //    mailFax.Attachments.Add(_View.PDFPath, Outlook.OlAttachmentType.olByValue, 1, "Transmittal_" + _View.TransmittalNo.ToString());

            //    mailFax.Send();
            //}
            //else
            //{
            //    throw new Exception("PDF file is not exist");
            //}
            //Outlook.MailItem mailOffshore = (Outlook.MailItem)OutApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
            //mailOffshore.To = getOffShoreAttn();//_View.Attn;
            //mailOffshore.CC = getOffShoreCc();//_View.CC;
            //mailOffshore.Subject = _View.Subject;
            //mailOffshore.BodyFormat = Outlook.OlBodyFormat.olFormatHTML;
            //mailOffshore.HTMLBody = db.GetBodyAttnEmail();
            //mailOffshore.Attachments.Add(_View.PDFPath, Outlook.OlAttachmentType.olByValue, 1, "Transmittal");

            //if (!string.IsNullOrEmpty(mailOnshore.To))
            //    mailOnshore.Send();
            //if (!string.IsNullOrEmpty(mailOffshore.To))
            //    mailOffshore.Send();
        }

    }
    public class EmailGoogleSender : EmailEngineBase
    {
        MailMessage mail;
       // private bool isLocal = false;
        private string user;
        private string pass;
        private bool useSSL;
        public EmailGoogleSender()
            : base("smtp.gmail.com", 587, "TestPtgdi@gmail.com")
        {

        }
        public void PrepareEmail(string send_to, string send_cc, string send_from, string subject, string body)
        {
            mail = new MailMessage();
            if (send_from == "")
                send_from = from_address;
            mail.From = new MailAddress(send_from);
            mail.Subject = subject;
            mail.Body = body;
            mail.IsBodyHtml = true;
            mail.Priority = MailPriority.Normal;

            if (!String.IsNullOrEmpty(send_to))
            {
                foreach (string email in send_to.Split(';'))
                {
                    if (email != "")
                        mail.To.Add(email);
                }
            }

            if (!String.IsNullOrEmpty(send_cc))
            {
                foreach (string email in send_cc.Split(';'))
                {
                    if (email != "")
                        mail.CC.Add(email);
                }
            }
            mail.Sender = mail.From;
        }
        public void SendSmtpEmail()
        {
            SmtpClient client = new SmtpClient();
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.Port = smtp_port;
            client.Host = smtp_address;

            if (client.Port != 25)
                client.EnableSsl = true;
            if (!(String.IsNullOrEmpty(user) || String.IsNullOrEmpty(pass)))
                client.Credentials = new NetworkCredential(user, pass);
#if !DEBUG
            client.Send(mail);
#else
            Debug.Print("From: {0}\r\nTo: {1}\r\nSubject: {2}\r\nBody: \r\n{3}",
                "eTransmittal System", mail.To.ToString(), mail.Subject, mail.Body);
#endif
        }
        public override void SendEmail(string send_to, string send_cc, string send_from, string subject, string body)
        {
            MailMessage mail = new MailMessage();
            if (send_from == "")
                send_from = from_address;
            mail.From = new MailAddress(send_from);
            mail.Subject = subject;
            mail.Body = body;
            mail.IsBodyHtml = true;
            mail.Priority = MailPriority.Normal;

            if (!String.IsNullOrEmpty(send_to))
            {
                foreach (string email in send_to.Split(';'))
                {
                    if (email != "")
                        mail.To.Add(email);
                }
            }

            if (!String.IsNullOrEmpty(send_cc))
            {
                foreach (string email in send_cc.Split(';'))
                {
                    if (email != "")
                        mail.CC.Add(email);
                }
            }

            mail.Bcc.Add("adam.ramdhani@ptgdi.com");     //FOR MONITORING EMAIL SENDING SUCCESS

            SmtpClient client = new SmtpClient();
            client.Port = smtp_port;
            client.Host = smtp_address;
            if (client.Port != 25)
                client.EnableSsl = true;
            client.Credentials = new NetworkCredential("A2damn@gmail.com", "12juli1981!");
            client.Send(mail);
        }

        public override void SendEmail(string send_to, string send_cc, string send_from, string subject, string body, string filePath)
        {
            MailMessage mail = new MailMessage();
            if (send_from == "")
                send_from = from_address;
            mail.From = new MailAddress(send_from);
            mail.Subject = subject;
            mail.Body = body;
            mail.IsBodyHtml = true;
            mail.Priority = MailPriority.Normal;

            if (!String.IsNullOrEmpty(send_to))
            {
                foreach (string email in send_to.Split(';'))
                {
                    if (email != "")
                        mail.To.Add(email);
                }
            }

            if (!String.IsNullOrEmpty(send_cc))
            {
                foreach (string email in send_cc.Split(';'))
                {
                    if (email != "")
                        mail.CC.Add(email);
                }
            }

            mail.Bcc.Add("adam.ramdhani@ptgdi.com");     //FOR MONITORING EMAIL SENDING SUCCESS
            Attachment att = new Attachment(filePath);
            att.Name = Path.GetFileName(filePath);
            SmtpClient client = new SmtpClient();
            client.Port = smtp_port;
            client.Host = smtp_address;
            if (client.Port != 25)
                client.EnableSsl = true;
            client.Credentials = new NetworkCredential("A2damn@gmail.com", "12juli1981!");
            client.Send(mail);
        }
    }
}
